#include "osd.h"
#include <qimage.h>

#include "CDGWidgetGL.h"

const int infoDimTime = 5; //sec

void osd::show(QString text)
{
    if (text.isEmpty())
       return;

    if (m_infoTexture)
       glDeleteTextures(1, &m_infoTexture);

    m_infoDim=0;
    
    QPixmap pix(512, 512);    
    QPainter p(&pix, this);
    p.fillRect(0, 0, pix.width(), pix.height(), Qt::black);
    p.setPen(Qt::white);
    QFont f ("Arial", 12, QFont::Normal);
    p.setFont (f);

    p.drawText(10, 10, pix.width() - 20, pix.height() - 20,
               Qt::AlignLeft, text);
    p.end();
    
    QImage img(pix.convertToImage());
    img = img.convertDepth(32);
    
    QImage tex = QGLWidget::convertToGLFormat(img);
    
    /* create the texture */
    glGenTextures(1, &m_infoTexture);
    glBindTexture(GL_TEXTURE_2D,m_infoTexture);

    /* actually generate the texture */
    glTexImage2D(GL_TEXTURE_2D, 0, 3, tex.width(), tex.height(), 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, tex.bits());

    /* enable linear filtering  */
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}

void osd::paintGL(void)
{
    //Info
    if (m_infoTexture)
    {
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        
        glMatrixMode(GL_TEXTURE);
        glLoadIdentity();
        
        glBindTexture(GL_TEXTURE_2D, m_infoTexture);
        glBegin(GL_QUADS);
        {
            glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
            glTexCoord2f(0.0f, 0.0f); glVertex2f(-0.75f, -0.75f);
            glTexCoord2f(1.0f, 0.0f); glVertex2f(+0.75f, -0.75f);
            glTexCoord2f(1.0f, 1.0f); glVertex2f(+0.75f, +0.75f);
            glTexCoord2f(0.0f, 1.0f); glVertex2f(-0.75f, +0.75f);
        }
        glEnd();

        // Update dim-in effect
        m_infoDim++;
        if(m_infoDim>(animTimer*infoDimTime))
        {
            glDeleteTextures(1, &m_infoTexture);
            m_infoTexture = 0;
        }
    }
}

void osd::clear()
{
    if (m_infoTexture)
    {
        glDeleteTextures(1, &m_infoTexture);
        m_infoTexture = 0;
    }
}

